import { useEffect, FC, ReactNode, useState, useRef } from 'react';
import { View, Text, Button } from '@tarojs/components'
import { AtForm, AtInput, AtButton, AtTextarea, AtFloatLayout } from 'taro-ui'
import { useSetState } from '@hooks/index.ts'
import './index.less';
import "taro-ui/dist/style/components/form.scss";
import { AtFormProps } from 'taro-ui/types/form';
import { Component } from '@tarojs/taro'
import MyCheckbox from '../myCheckbox'
import SingleAccountEdit from '../singleAccountEdit'
import Taro from '@tarojs/taro';
import { updateAccount, allPropertiesNotEmpty, validateData, deepArrayEqual } from '@untils/functions'
import { defaultSingleInfo } from '@untils/common'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import { saveSingleAccount, saveBatchAccounts, getSingleAccount, getBatchAccount } from '@api/account.ts'


// 定义 Props 接口
interface Props {
  children?: ReactNode;
  personalInfo: Record<any, any>,
  initalBatchInfo: string
  initValue: Record<any, any>
}
enum QueryType {
  single = 'single',
  batch = 'batch'
}
type UserInfoType = {
  id_number_pre: string | number,
  id_number_suf: string | number,
  last_name: string,
  phone_pre: number,
  phone_suf: number
}
type QueryTypeUnion = keyof typeof QueryType;

const messageInfo = '姓名 身份证前三位 身份证后四位 号码前三位 号码后四位。间隔为一个空格，请务必注意哦'
const placeholder = '马云 513 3250 130 8325 李嘉诚 512 3323 181 2343'

const Index: FC<Props> = () => {
  const { single, batch } = QueryType
  const [queryType, setQueryType] = useState<QueryTypeUnion>(single)
  const [userInfo, setUserInfo] = useSetState<UserInfoType>({})
  const formRef = useRef<Component<AtFormProps, any, any>>(null);
  const [batchInfo, setBatchInfo] = useState<Array<UserInfoType>>([])
  const [batchString, setBatchString] = useState('')
  const [checkedId, setCheckedId] = useState('')
  const [openSingleAccountFloat, setOpenSingleAccountFloat] = useState(false)
  const [transformVisible, setTransformVisible] = useState(false)
  const editBatchAccount = useRef({})
  const batchAccountData = useRef([])

  const getSingleData = async () => {
    const result = await getSingleAccount()
    if (result?.code === 200) {
      const data = result?.data
      if (Object.keys(data).length) {
        const { last_name, phone_pre, phone_suf, id_number_pre, id_number_suf } = data
        const infoData = {
          last_name, phone_pre, phone_suf, id_number_pre, id_number_suf
        }
        Taro.setStorageSync('singleAccountInfo', infoData)
        setUserInfo(infoData);
      } else {
        Taro.setStorageSync('singleAccountInfo', defaultSingleInfo)
        setUserInfo(defaultSingleInfo);
      }
    }
  }
  const getBatchData = async () => {
    const result = await getBatchAccount()
    if (result?.code === 200) {
      const data = result?.data || []
      Taro.setStorageSync('batchAccountInfo', data)
      setBatchInfo(data)
    }
  }
  useEffect(() => {
    // 任何你需要在组件挂载时执行的副作用
    const params = Taro.getCurrentInstance().router.params || { type: single };
    setQueryType(params?.type as QueryTypeUnion)
    const singleAccountInfo = Taro.getStorageSync('singleAccountInfo')
    const batchAccountInfo = Taro.getStorageSync('batchAccountInfo') || []
    if (!singleAccountInfo) {
      getSingleData()
    } else {
      setUserInfo(singleAccountInfo)
    }
    if (!batchAccountInfo.length) {
      getBatchData()
    } else {
      setBatchInfo(batchAccountInfo)
    }
  }, []);

  const switchQueryType = (type: QueryTypeUnion) => {
    setQueryType(type)
  }

  const handleChange = (type: string, value: string): void => {
    setUserInfo({
      [type]: value
    })
  }

  const hangleBatchInfo = (value: string) => {
    setBatchString(value)
  }


  const NoAccount = () => {
    return <View className='singleContent'>
      <Text className='name'>xx</Text>
      <Text className='idNumber'>xxx-xxxx</Text>
      <Text className='phoneNumber'>xxx-xxxx</Text>
    </View >
  }

  const renderSingleAccountList = (data = {}) => {
    if (queryType != single) {
      return ''
    }
    if (!Object.keys(data)) {
      return <NoAccount />
    }
    const { last_name, phone_pre, phone_suf, id_number_pre, id_number_suf } = data as UserInfoType
    return <View className='singleContent'>
      <Text className='name'>{last_name || '马云'}</Text>
      <Text className='idNumber'>{id_number_pre || 'xxx'}-{id_number_suf || 'xxxx'}</Text>
      <Text className='phoneNumber'>{phone_pre || 'xxx'}-{phone_suf || 'xxxx'}</Text>
    </View>
  }

  const deleteAccount = (id: string) => {
    let cloneData = batchInfo.filter(item => item.id != id);
    setBatchInfo(cloneData)
  }

  const editAccount = (data) => {
    editBatchAccount.current = data
    setOpenSingleAccountFloat(true)
  }
  const hangleCheck = (id) => {
    if (id == checkedId) {
      setCheckedId('')
    } else {
      setCheckedId(id)
    }
  }
  const renderBatchAccountList = (data) => {
    if (queryType != batch) {
      return ''
    }
    if (!data.length) {
      return <NoAccount />
    }
    return <>
      {
        data.map(item => {
          const { id_number_pre, id_number_suf, phone_pre, phone_suf, last_name, id } = item
          return <View className='singleContent'>
            <View className='name batch-name' onClick={() => hangleCheck(id)} >
              <MyCheckbox checked={id == checkedId} onChange={() => hangleCheck(id)} />
              <Text>{last_name}</Text>
            </View>
            <Text className='idNumber'>{id_number_pre}-{id_number_suf}</Text>
            <View className='phoneNumber'>
              <Text>{phone_pre}-{phone_suf}</Text>
              {
                id == checkedId &&
                <>
                  <Text className='editAccount' onClick={() => editAccount(item)}>编辑</Text>
                  <Text className='deleteAccount' onClick={() => deleteAccount(id)}>删除</Text>
                </>
              }
            </View>
          </View>
        })
      }
    </>
  }
  const hangleAtFloatClose = () => {
    editBatchAccount.current = {}
    setOpenSingleAccountFloat(false)
  }

  // 批量的-单个编辑数据回调
  const singleAccountEditCallback = (value1, value2) => {
    const newEditData = {
      ...editBatchAccount.current,
      [value1]: value2
    }
    const newData = updateAccount(checkedId, newEditData, batchInfo)
    setBatchInfo(newData)
  }

  const saveSingle = async (params) => {
    const result = await saveSingleAccount(params)
    if (result?.code === 200) {
      Taro.setStorageSync('singleAccountInfo', userInfo)
      Taro.showToast({ title: '保存成功', icon: 'none' });
    }
  }

  // 单个账号数据保存
  const singleSave = () => {
    const { isValid, message } = validateData(userInfo)
    if (!isValid) {
      Taro.showToast({ title: message, icon: 'none' });
      return
    }
    saveSingle({
      ...userInfo
    })
  }

  // 单个账号重置
  const singleReset = () => {
    setUserInfo(defaultSingleInfo)
  }

  // 批量账号操作
  const transformData = () => {
    if (!batchString) {
      Taro.showToast({ title: '您还未输入任何数据', icon: 'none' });
      return
    }
    const transformData = parseInputToObjects(batchString)
    if (!transformData) {
      return
    }
    batchAccountData.current = transformData
    setTransformVisible(true)
  }

  const batchSaveNow = () => {
    const batchAccountInfo = Taro.getStorageSync('batchAccountInfo') || []
    const isEqual = deepArrayEqual(batchAccountInfo, batchInfo)
    if (isEqual) {
      Taro.showToast({ title: '数据未变动，无需保存', icon: 'none', duration: 2000 });
      return
    }
    saveBatch({ accounts: batchInfo })
  }

  function parseInputToObjects(input) {
    // 将输入文本按照 '-' 分割成数组
    const parts = input.split(' ');
    // 初始化结果数组
    const result = [];
    // 遍历整个输入，处理每5个部分
    for (let i = 0; i < parts.length; i += 5) {
      const last_name = parts[i];
      const id_number_pre = parts[i + 1] || '';
      const id_number_suf = parts[i + 2] || '';
      const phone_pre = parts[i + 3] || '';
      const phone_suf = parts[i + 4] || '';

      // 验证各部分格式是否正确
      if (
        !last_name ||
        phone_pre?.length !== 3 || isNaN(phone_pre) ||
        phone_suf?.length !== 4 || isNaN(phone_suf) ||
        id_number_pre?.length !== 3 || isNaN(id_number_pre) ||
        id_number_suf?.length !== 4
      ) {
        Taro.showToast({ duration: 2000, title: '输入的某部分格式不正确', icon: 'none' });
        return;
      }
      // 构建对象并加入结果数组
      result.push({
        last_name,
        phone_pre,
        phone_suf,
        id_number_pre,
        id_number_suf
      });
    }
    return result;
  }

  const saveBatch = async (params, callback = () => { }) => {
    const result = await saveBatchAccounts(params)
    if (result.code === 200) {
      setBatchInfo(params.accounts)
      Taro.setStorageSync('batchAccountInfo', params.accounts)
      Taro.showToast({ title: '保存成功', icon: 'none' });
    }
    callback()
  }

  const sureSaved = () => {
    saveBatch({ accounts: batchAccountData?.current || [] }, () => { setTransformVisible(false) })
  }
  return (
    <View className='accountManage'>
      <View className='winnerQuery'>
        <View className='queryType'>
          <Text className='header'>
            <Text className={`${queryType === single ? 'checked' : 'single'}`} onClick={() => switchQueryType(single)}>单个账号</Text>
            <Text className={`${queryType === batch ? 'checked' : 'batch'}`} onClick={() => switchQueryType(batch)}>批量账号</Text>
          </Text>
        </View>
        {
          queryType === single && <View className='singleUserInfo'>
            <AtForm
              ref={formRef}
              className='userInfoForm'
            >
              <AtInput
                name='last_name'
                title='姓名：'
                type='text'
                placeholder='请输入'
                value={userInfo.last_name as string}
                onChange={(value: string) => handleChange('last_name', value)}
              />
              <View className='idCardInfo'>
                <AtInput
                  name='id_number_pre'
                  title='身份证：'
                  type='number'
                  maxLength={3}
                  placeholder='前三位'
                  value={userInfo.id_number_pre as string}
                  onChange={(value: string) => handleChange('id_number_pre', value)}
                />
                <AtInput
                  name='id_number_suf'
                  type='number'
                  maxLength={4}
                  placeholder='后四位'
                  value={userInfo.id_number_suf as string}
                  onChange={(value: string) => handleChange('id_number_suf', value)}
                />
              </View>
              <View className='phoneNumberInfo'>
                <AtInput
                  name='phone_pre'
                  title='手机号码：'
                  type='number'
                  border={false}
                  placeholder='前三位'
                  maxLength={3}
                  value={userInfo.phone_pre as string}
                  onChange={(value: string) => handleChange('phone_pre', value)}
                />
                <AtInput
                  name='phone_suf'
                  type='number'
                  placeholder='后四位'
                  value={userInfo.phone_suf as string}
                  onChange={(value: string) => handleChange('phone_suf', value)}
                  border={false}
                  maxLength={4}
                />
              </View>
            </AtForm>
            <View className='buttonList'>
              <AtButton className='submit' onClick={singleSave}>保存</AtButton>
              <AtButton className='reset' onClick={(singleReset)}>重置</AtButton>
            </View>
          </View>
        }

        {queryType === batch &&
          <><View className='batchUserInfo'>
            <Text className='dataChange'>批量数据转换</Text>
            <Text className='infoMessage'>格式：{messageInfo}</Text>
            <AtTextarea
              autoFocus={true}
              value={batchString}
              count={false}
              onChange={hangleBatchInfo}
              maxLength={20000}
              placeholder={placeholder}
              height={200}
              placeholderClass='batchTextarea'
            />
          </View>
            <View className='buttonList'>
              <AtButton className='submit' onClick={transformData}>转换数据</AtButton>
              <AtButton className='reset' onClick={() => setBatchString('')}>重置</AtButton>
            </View>
          </>
        }
      </View>
      <View className='accountList'>
        <View className='title'>已保存数据{queryType === single ? ' (单个)' : ' (批量)'}</View>
        <View className='list'>
          <View className='single'>
            <Text className='name'>姓名</Text>
            <Text className='idNumber'>身份证</Text>
            <Text className='phoneNumber'>手机号码</Text>
          </View>
          {renderSingleAccountList(userInfo)}
          {renderBatchAccountList(batchInfo)}
        </View>
        {
          queryType === batch && batchInfo.length ? <View className='savedButton'>
            <AtButton className='saveNow' onClick={batchSaveNow}>立即保存</AtButton>
          </View> : ''
        }
      </View>

      <AtFloatLayout isOpened={openSingleAccountFloat} title="修改信息" onClose={hangleAtFloatClose}>
        <SingleAccountEdit
          user_info={editBatchAccount.current as UserInfoType}
          onChange={singleAccountEditCallback}
        />
        <Text className='info-message'>提示：更改后的数据需要点击“立即保存”按钮才会真正更新</Text>
      </AtFloatLayout>

      <AtModal isOpened={transformVisible} className='transformModal'>
        <AtModalHeader>温馨提示</AtModalHeader>
        <AtModalContent>
          新数据将覆盖下方”已保存数据“，您确定保存吗？
        </AtModalContent>
        <AtModalAction>
          <Button className='cancle' onClick={() => setTransformVisible(false)}>取消</Button>
          <Button className='sureDo' onClick={() => sureSaved()}>确定</Button>
        </AtModalAction>
      </AtModal>
    </View>
  );
};

export default Index;
